package com.fh.controller.wechatapp;

import com.fh.controller.base.BaseController;
import com.fh.dto.*;
import com.fh.entity.HttpResult;
import com.fh.entity.Page;
import com.fh.service.airsys.airlineemployee.AirlineEmployeeService;
import com.fh.service.airsys.airlinerummery.AirlineRummeryService;
import com.fh.service.airsys.common.SendSMS;
import com.fh.service.airsys.registeronlinetran.RegisteronLineTranService;
import com.fh.service.airsys.transactiondetails.TransactionDetailsService;
import com.fh.service.airsys.verificationcode.VerificationCodeService;
import com.fh.service.transaction.OnLineTranService;
import com.fh.service.wechat.WeChatAccService;
import com.fh.util.DateUtil;
import com.fh.util.PageData;
import com.fh.util.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/8/21.
 */
@Controller @RequestMapping(value = "/wechat/acc/")
public class WeChatAccController extends BaseController {

    @Autowired
    WeChatAccService weChatAccService;
    @Autowired
    AirlineEmployeeService airlineEmployeeService;
    @Autowired
    OnLineTranService onLineTranService;
    @Autowired
    VerificationCodeService verificationCodeService;//验证码
    @Autowired
    SendSMS sendSMS;//短信发送
    @Resource(name="transactiondetailsService")
    private TransactionDetailsService transactiondetailsService;
    @Resource(name="registeronlinetranService")
    private RegisteronLineTranService registeronlinetranService;
    @Autowired
    private AirlineRummeryService airlineRummeryService;

    @RequestMapping(value = "getSessionKey")
    @ResponseBody
    public Map getSessionKey(){
        PageData pd = this.getPageData();
        return weChatAccService.getSessionKey(pd);
    }


    @RequestMapping(value = "getAirEmpInfo")
    @ResponseBody
    public HttpResult getAirEmpInfo(Page page){
        PageData pd = new PageData();
        pd = this.getPageData();
        pd.put("OPEN_ID",pd.getString("openId"));
        try {
            PageData empData = airlineEmployeeService.findById(pd);
            if(empData == null){
                return HttpResult.ERROR("55556","该员工信息未录入系统，请联系系统管理员");
            }
            AirEmpInfo info = new AirEmpInfo(empData);
            return HttpResult.OK(info);
        } catch (Exception e) {
            e.printStackTrace();
            return HttpResult.ERROR("55555",e.getMessage());
        }
    }

    @RequestMapping(value = "onlineTran")
    @ResponseBody
    public HttpResult onlineTran(TranRequest request){
        request.setTranType("1011");
        request.setTranAmt(request.getTranAmt()*-1);
        return onLineTranService.tranExce(request);
    }

    @RequestMapping(value = "gerTranList")
    @ResponseBody
    public HttpResult gerTranList(TranListReuest tranListReuest){
        Page<TranListResponse> page = new Page<TranListResponse>();
        if(tranListReuest.getCount()==null || tranListReuest.getCount() == 0){
            page.setShowCount(10);
        }
        else
            page.setShowCount(tranListReuest.getCount());
        if(tranListReuest.getPageNo() == null || tranListReuest.getPageNo() == 0){
            tranListReuest.setPageNo(1);
        }
        page.setCurrentPage(tranListReuest.getPageNo());
        PageData pd = new PageData();
        try {
            pd.put("EI_EMINFO",tranListReuest.getEmpId());
            PageData empData = airlineEmployeeService.findById(pd);
            pd.put("AIRLINEEMPLOYEE_ID",empData.get("AIRLINEEMPLOYEE_ID"));
            pd.put("TRAN_TYPE",empData.get("tranType"));
            page.setPd(pd);
            List<PageData> varList = transactiondetailsService.list(page);
            List<TranListResponse> list = TranListResponse.getList(varList);
            com.fh.dto.Page<TranListResponse> result = new com.fh.dto.Page<TranListResponse>(page,list);
            return HttpResult.OK(result);
        } catch (Exception e) {
            return HttpResult.ERROR("55555",e.getMessage());
        }
    }

    @RequestMapping(value = "sendVerifiCode")
    @ResponseBody
    public HttpResult sendVerifiCode(VerifiCode code){
        String date = DateUtil.getYYYYMMDDHHMMSS();
        PageData pageData = new PageData();
        pageData.put("TELNUM",code.getTelNum());
        PageData codeDate = null;
        try {
            codeDate = verificationCodeService.findById(pageData);
        } catch (Exception e) {
            HttpResult.ERROR("55551","验证码获取异常");
        }
        Integer vCode = Tools.getRandomNum();
        try{
            if(codeDate == null){
                codeDate = new PageData();
                codeDate.put("VERIFICATIONCODE_ID",this.get32UUID());
                codeDate.put("CREATE_TIME",date);
                codeDate.put("CODE",vCode.toString());
                codeDate.put("TELNUM",code.getTelNum());
                verificationCodeService.save(codeDate);
            }
            else{
                codeDate.put("CREATE_TIME",date);
                codeDate.put("CODE",vCode.toString());
                verificationCodeService.edit(codeDate);
            }
        }catch (Exception e){
            e.printStackTrace();
            return HttpResult.ERROR("55552","验证码更新异常");
        }
        List<String> context = new ArrayList<String>();
        context.add(vCode.toString());
        context.add("3");
        Integer result = sendSMS.send(code.getTelNum(),context,"1");
        if(result == null || result == 0){
            return HttpResult.ERROR("55559","验证短信发送失败");
        }
        Map<String,String> map = new HashMap<String, String>();
        map.put("telNum",code.getTelNum());
        return HttpResult.OK(map);
    }

    @RequestMapping(value = "login")
    @ResponseBody
    public HttpResult login(String openId,String code,String telNum){
        PageData pd = new PageData();
        pd.put("TELNUM",telNum);
        try {
            PageData codeData =  verificationCodeService.findById(pd);
            if(codeData != null && codeData.size()>0){
                String vCode = codeData.getString("CODE");
                if(!vCode.equals(code)){
                    return HttpResult.ERROR("55557","验证码错误");
                }
                Long nowDate = Long.parseLong(DateUtil.getYYYYMMDDHHMMSS());
                Long codeDate = Long.parseLong(codeData.getString("CREATE_TIME"))+180l;
                if(nowDate > codeDate){
                    //return HttpResult.ERROR("55558","验证码超时，请重新获取");
                }
                PageData empData = airlineEmployeeService.findById(pd);
                if(empData == null){
                    return HttpResult.ERROR("55556","该员工信息未录入系统，请联系系统管理员");
                }
                else{
                    empData.put("OPEN_ID",openId);
                    airlineEmployeeService.edit(empData);
                    AirEmpInfo info = new AirEmpInfo(empData);
                    return HttpResult.OK(info);
                }
            }
            else{
                return HttpResult.ERROR("55554","验证码信息不存在，请重新发送");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return HttpResult.ERROR("55553","登录异常");
        }
    }
    @RequestMapping(value = "getShopDetailByQrCode",method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getShopDetailByQrCode(Page page){
        PageData pd = new PageData();
        pd = this.getPageData();
        String qrCode=pd.getString("qRCode");
        ShopDetailByQrCodeResponse response=new ShopDetailByQrCodeResponse();
        response.setqRCode(qrCode);
        response.setMerchantName("龙华商品有限公司");
        response.setShopName("9天连锁酒店");
        response.setPsamId("2017091011");
        response.setTermNo("100000000001");
        response.setShopType("酒店");
        return HttpResult.OK(response);
    }

    @RequestMapping(value = "getRegisterList")
    @ResponseBody
    public HttpResult getRegisterList(TranRegisterRequest request){
        Page<TranListResponse> page = new Page<TranListResponse>();
        if(request.getCount()==null || request.getCount() == 0){
            page.setShowCount(10);
        }
        else
            page.setShowCount(request.getCount());
        page.setCurrentPage(request.getPageNo());
        PageData pd = new PageData();
        try {
            pd.put("EI_CODE",request.getEmpId());
            pd.put("RL_STATE",request.getState());
            pd.put("RL_TYPE",request.getType());
            page.setPd(pd);
            List<PageData>	varList = registeronlinetranService.list(page);	//列出RegisteronLineTran列表
            List<TranRegisterResponse> list = TranRegisterResponse.getList(varList);
            com.fh.dto.Page<TranRegisterResponse> result = new com.fh.dto.Page<TranRegisterResponse>(page,list);
            return HttpResult.OK(result);
        } catch (Exception e) {
            return HttpResult.ERROR("55555",e.getMessage());
        }
    }

    @RequestMapping(value = "getRummeryById")
    @ResponseBody
    public HttpResult getRummeryById(String id){
        PageData pd = new PageData();
        try {
            pd.put("AIRLINERUMMERY_ID",id);
            pd = airlineRummeryService.findById(pd);
            RummeryInfo info = new RummeryInfo(pd);
            return HttpResult.OK(info);
        } catch (Exception e) {
            return HttpResult.ERROR("55555",e.getMessage());
        }
    }

    @RequestMapping(value = "tranRegister")
    @ResponseBody
    public HttpResult TranRegister(String tson,String empId,String orgId){
        try {
            PageData pd = new PageData();
            pd.put("RL_CODE",tson);
            pd.put("EI_CODE",empId);
            pd.put("AL_CODE",orgId);
            PageData registeron = registeronlinetranService.findById(pd);
            if(registeron == null){
                return HttpResult.ERROR("55560","无补录信息");
            }
            if((Integer)registeron.get("RL_STATE") == 2){
                return HttpResult.ERROR("55561","补录交易已完成");
            }
            if((Integer)registeron.get("RL_STATE") == 3){
                return HttpResult.ERROR("55562","财务已确认无效补录交易");
            }
            if((Integer)registeron.get("RL_STATE") == 4){
                return HttpResult.ERROR("55563","过期补录交易");
            }
            TranRequest request = new TranRequest();
            request.setTranType("1014");
            request.setEmpId(empId);
            request.setOrgId(orgId);
            request.setRummeryId(registeron.getString("RI_CODE"));
            request.setTranAmt((Integer) registeron.get("RL_AMOUNT")*-1);
            request.setTson(registeron.getString("RL_CODE"));
            HttpResult result = onLineTranService.tranExce(request);
            if(result.code == "00000"){
                registeron.put("RL_TYPE",1);
                registeron.put("RL_STATE",2);
                registeron.put("RL_USERNAME",empId);
                registeron.put("RL_FINAL_TIME",DateUtil.getTime());
                registeronlinetranService.edit(registeron);
            }
            return result;

        } catch (Exception e) {
            return HttpResult.ERROR("55555",e.getMessage());
        }
    }


}
